<template>
  <div class="course container">
    <div class="header">
      <list-header @theParams="handleParams" :params="params"></list-header>
    </div>
    <edu-course-list
      v-if="courseList.length > 0"
      :courseList="courseList"
      @next="handleNext"
    ></edu-course-list>
    <edu-no-data v-else></edu-no-data>
    <edu-pagination @handleCurrentChange="handleCurrentChange"></edu-pagination>
  </div>
</template>

<script>
import ListHeader from './components/listHeader'
import EduCourseList from '@/components/EduCourseList'
import EduNoData from '@/components/EduNoData'
import EduPagination from '@/components/EduPagination'

export default {
  components: {
    ListHeader,
    EduCourseList,
    EduNoData,
    EduPagination
  },
  inject: ['reload'],
  data() {
    return {
      courseList: [],
      params: {}
    }
  },
  watch: {
    $route(n, o) {
      if (n != o) {
        this.params = {}
        this.$store.dispatch('paginate/setPaginate', {
          currentPage: 1
        })
        this.getCourseInfo()
      }
    }
  },
  methods: {
    // 分页
    handleCurrentChange() {
      this.getCourseInfo()
    },
    handerParams(data) {
      // 去除对象空值key
      for (const key in data) {
        if (data[key] === '' || data[key] === undefined) {
          delete data[key]
        }
      }
    },
    // 请求列表数据
    getCourseInfo() {
      let _this = this
      _this.handerParams(_this.params)
      this.$api.getCourseList(
        {
          ...this.$route.query,
          course_type: this.$route.query.type,
          page: this.$store.getters['paginate/page'],
          count: 24
        },
        res => {
          _this.handleGetDataSucc(res)
        }
      )
    },
    handleGetDataSucc(res) {
      if (res.data) {
        const data = res.data
        this.courseList = data.data
        this.$store.dispatch('paginate/setPaginate', {
          listRows: 24,
          total: data.total
        })
      }
    },
    // 处理筛选返回参数跟新数据
    handleParams(val) {
      this.$router.push({
        path: this.$route.fullPath,
        query: val
      })
    },
    // 下一页
    handleNext(item) {
      this.$router.push({ path: '/course/' + item.id })
    }
  },
  created() {
    this.getCourseInfo()
  },
  destroyed() {
    this.$store.commit('paginate/SET_PAGINATE_DEFAULT')
  }
}
</script>

<style lang="scss" scoped>
.course {
  margin-top: 10px;
  ::v-deep .course-list {
    margin-top: 15px;
  }
  .header {
    padding: 24px;
    background-color: #ffffff;
  }
}
</style>
